package controller;

import command.BinderCommand;
import entity.Address;
import entity.Point;
import org.omg.PortableServer.POA;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/binder")
public class BinderController {


    @InitBinder
    public void init(WebDataBinder dataBinder){
        System.out.println("BinderController.init()");

        PropertyEditorSupport pointEditor=new PropertyEditorSupport(){
            @Override
            public void setAsText(String text) throws IllegalArgumentException {

                if(text==null||"".equals(text.trim())){
                    return;
                }

                text=text.substring(1,text.length()-1);
                String[] s=text.split(",");

                Point point=new Point();
                point.setX(Double.parseDouble(s[0]));
                point.setY(Double.parseDouble(s[1]));

                setValue(point);
            }

            @Override
            public String getAsText() {
                Point point= (Point) getValue();
                return "("+point.getX()+","+point.getY()+")";
            }
        };


        dataBinder.registerCustomEditor(Point.class,pointEditor);

//        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));







    }


    @RequestMapping("/show")
    public String show(BinderCommand binderCommand){
        System.out.println("BinderController.show()");


        Point point=new Point();
        point.setX(5.0);
        point.setY(7.0);
        binderCommand.setPoint(point);


        Point p=new Point();
        p.setX(8.0);
        p.setY(9.0);
        binderCommand.setP(p);


        binderCommand.setBirthday(new Date());

        Address address=new Address();
        address.setProvince("江苏省");
        address.setCity("南京市");

        binderCommand.setAddress(address);

        return "binder";
    }

    @RequestMapping("/submit")
    public String submit(BinderCommand binderCommand, Errors errors){
        System.out.println("BinderController.submit()");

        if(errors.hasErrors()){
            return "binder";
        }


        System.out.println(binderCommand);

        return "redirect:/binder/show";
    }
}
